import React from 'react';
import { Button, Card, Col, Icon, Modal, Popconfirm, Row, Spin, Tooltip, Upload } from 'antd';
import styles from './index.less';
import { saveAs } from 'file-saver';
import { connect } from 'dva';
import BaseComponent from '@/components/BaseComponent';
import SearchForm from './SearchForm';
import EditView from './EditView';
import PreviewView from './PreviewView';
import ProTable from '@ant-design/pro-table';
import PermissionsWidget from '@/components/PermissionsWidget';
import chushixiaoyanguize from '@/assets/chushixiaoyanguize.png';
import binglidaima from '@/assets/binglidaima.png';
import {
  dataInitDiagnosisNounsDownloadUrl,
  dataInitTemplateDownloadUrl,
  dataInitUploadTipEnable,
} from '@/defaultSettings';
import moment from 'moment';
import { PhotoProvider, PhotoView } from 'react-photo-view';

const { confirm } = Modal;

@connect(({ user, initialdatareporting, loading }) => ({
  currentUser: user.currentUser,
  data: initialdatareporting.data,
  isLoading: loading.effects['initialdatareporting/listAllTableData'],
  isPreparing: loading.effects['initialdatareporting/listAllTableColumn'],
  isDelSingleing: loading.effects['initialdatareporting/deleteById'],
  isFinding: loading.effects['initialdatareporting/findById'],
  isDeleteAlling: loading.effects['initialdatareporting/oneClickDelete'],
  isSaveOfficeing: loading.effects['initialdatareporting/insertOfficeInfo'],
  isBatchDeling: loading.effects['initialdatareporting/batchDeletion'],
  isUpdateing: loading.effects['initialdatareporting/updateRecord'],
  isDownloading: loading.effects['initialdatareporting/exportSysteminitImportInfo'],
  isExporting: loading.effects['initialdatareporting/exportSysteminitImportInfo'],
  isLoadingCitys: loading.effects['orgsetting/getAllProvinceCity'],
  isLoadingStreets: loading.effects['orgsetting/getDistrictAndStreet'],
}))
class InitialDataReporting extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 被选中的行
      selectedRows: [],
      // 被选中后的行的id
      selectedRowKeys: [],
      // columns
      tableColumns: [],
      // 默认将被取消选中的column
      columnsStateMap: {},
      // 食管病理诊断代码
      sgblCode: [],
      // 是否活检
      isHj: [],
      // 十二指肠病理诊断代码
      sezccode: [],
      // 是否无痛
      ache: [],
      // 对象来源
      zldxLy: [],
      // 诊疗方式
      zlFs: [],
      // 染色类别
      dye: [],
      // Hp检测结果
      Hp: [],
      // Hp检测方法
      hpjcjg: [],
      // 贲门病理诊断代码
      bmblCode: [],
      // 胃病理诊断代码
      wblCode: [],
      //性别
      xbcode: [],
      //是否有错误
      isHaveError: [],
      // 被选中的记录
      record: {},
      // 编辑视图的显示状态
      editViewVisible: false,
      // 详情视图的显示状态
      previewViewVisible: false,
      // 是否正在上传附件
      uploadLoading: false,
      // 附件列表
      files: [],
      tag1: [],
      tag2: [],
      tag3: [],
      tag4: [],
      tag5: [],
      //内镜诊断详情
      //食管数据集合
      sg: [],
      //贲门数据集合
      bm: [],
      //胃数据集合
      w: [],
      //用户权限
      roles: ['ROLE_ADMIN', 'ROLE_DEV', 'ROLE_MANAGER'],
      // 是否是管理员
      isAdmin: false,
      //城市集合
      cities: [],
      //区县街道集合
      districtAndStreet: [],
    };
  }

  componentDidMount() {
    const { orgName = '' } = this.props.currentUser;
    const isAdmin = this.checkIsAdmin(this.props.currentUser);
    this.setState({ isAdmin });
    // todo: 此处需要修改为更具特殊字段进行配置,目前的解决方案仅为演示时使用
    if (
      dataInitUploadTipEnable &&
      orgName.indexOf('疾控中心') == -1 &&
      orgName.indexOf('疾病预防') == -1
    ) {
      Modal.warning({
        centered: true,
        title: '温馨提醒',
        content: (
          <div style={{ color: 'red' }}>
            <p>初始数据上报：每月15日24时，平台将自动停止接受上月初始数据上报</p>
          </div>
        ),
        okText: '确认',
        cancelText: '取消',
      });
    }
    this.dictListAllByCode();
    this.listAllTableColumn();
    if (isAdmin) {
      // 读取城市
      this.getAllCities().then(list => {
        if (list) {
          this.setState({ cities: list }, () => {
            this.searchform.loadCompleted();
          });
          if (list[0]) {
            this.getDistrictAndStreet(list[0].id);
          }
        }
      });
    }
  }

  listAllTableColumn = () => {
    this.execHttp('initialdatareporting/listAllTableColumn', {}).then(resp => {
      if (resp) {
        const { success, data } = resp;
        let tableColumns = [];
        if (success) {
          tableColumns = data.colums;
        }
        this.setState(
          {
            tableColumns,
          },
          () => {
            this.initColumnsStateMap();
            this.listAllByPage({});
          }
        );
      }
    });
  };

  listAllByPage = params => {
    // 获取搜索框中的值
    const data = this.searchform.getData();
    this.execHttp('initialdatareporting/listAllTableData', {
      currentPage: 1,
      pageSize: 10,
      user: this.props.currentUser.id,
      ...data,
      ...params,
    });
  };

  /**点击获取省下面的城市*/
  getAllCities = () => {
    return new Promise((resolve, reject) => {
      this.execHttp('orgsetting/getAllProvinceCity', {
        parentRegionCode: '340000',
        user: this.props.currentUser.id,
      }).then(resp => {
        if (resp && resp.success) {
          const {
            success,
            data: { list },
          } = resp;
          if (success) {
            return resolve(list);
          }
        }
      });
    });
  };

  /**获取城市下的区街道信息*/
  getDistrictAndStreet = val => {
    this.execHttp('orgsetting/getDistrictAndStreet', {
      parentRegionCode: val,
    }).then(resp => {
      if (resp && resp.success) {
        const { success, data } = resp;
        if (success) {
          this.setState({
            districtAndStreet: data.list,
          });
        }
      }
    });
  };

  /**
   * 删除单条数据
   * @param id
   */
  deleteById = ({ id }) => {
    if (this.props.isDelSingleing) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('initialdatareporting/deleteById', { id })
      .then(resp => {
        hide();
        const { success, message } = resp;
        if (success) {
          this.successMessage(message);
          this.listAllByPage({});
        } else {
          this.errorMessage(message);
        }
      })
      .catch(reason => {
        hide();
      });
  };

  /**
   * 更新数据
   * @param data
   */
  updateRecord = ({ data, skip = false }) => {
    if (this.props.isUpdateing) {
      return;
    }
    const hide = this.loadingMessage('正在更新,请稍后...');
    this.execHttp('initialdatareporting/updateRecord', {
      user: this.props.currentUser.id,
      skip: skip ? 1 : 0,
      ...data,
    })
      .then(resp => {
        hide();
        const { success, message } = resp;
        if (success) {
          this.setState(
            {
              editViewVisible: false,
            },
            () => {
              this.successMessage(message);
              this.listAllByPage({});
            }
          );
        } else {
          if (message && message != '') {
            const messages = message.split('|').map((item, index) => {
              return (
                <div key={index} style={{ fontWeight: '700' }}>
                  {`${index + 1}.${item}`}
                </div>
              );
            });
            confirm({
              title: '数据验证未通过',
              content: messages,
              okText: '继续保存',
              okType: 'danger',
              chancelText: '取消',
              onOk: () => {
                this.updateRecord({ data: data, skip: true });
              },
              onCancel() { },
            });
          }
        }
      })
      .catch(reason => {
        hide();
      });
  };

  /**
   * 查询单条记录
   * @param id
   */
  findById = ({ id }) => {
    return new Promise((resolve, reject) => {
      if (this.props.isFinding) {
        return;
      }
      const hide = this.loadingMessage('操作中,请稍后...');
      this.execHttp('initialdatareporting/findById', { id })
        .then(resp => {
          hide();
          const {
            success,
            message,
            data: { response, detailMap },
          } = resp;
          const { sg, bm, w } = detailMap;
          if (success) {
            this.setState(
              {
                record: response,
                sg,
                bm,
                w,
              },
              () => {
                resolve();
              }
            );
          } else {
            this.errorMessage(message);
            reject();
          }
        })
        .catch(reason => {
          hide();
          reject();
        });
    });
  };

  dictListAllByCode = () => {
    this.execHttp('cersysdict/dictListAllByCode', {}).then(resp => {
      const { success, data } = resp;
      if (success) {
        this.setState({
          //食管病理诊断代码
          sgblCode: data.sgbl_code,
          //是否活检
          isHj: data.is_hj,
          //十二指肠病理诊断代码
          sezccode: data.sezc_code,
          //是否无痛
          ache: data.ache,
          //对象来源
          zldxLy: data.zldx_ly,
          //诊疗方式
          zlFs: data.zl_fs,
          //染色类别
          dye: data.dye,
          //Hp检测结果
          Hp: data.Hp,
          //Hp检测方法
          hpjcjg: data.hpjcjg,
          //贲门病理诊断代码
          bmblCode: data.bmbl_code,
          //胃病理诊断代码
          wblCode: data.wbl_code,
          //性别
          xbcode: data.xb_code,
          //是否有错误
          isHaveError: data.is_have_error,
          //tag1
          tag1: data.tag1,
          //tag2
          tag2: data.tag2,
          //tag3
          tag3: data.tag3,
          //tag4
          tag4: data.tag4,
          //tag5
          tag5: data.tag5,
        });
      }
    });
  };

  //初始化columnsStateMap
  initColumnsStateMap = () => {
    const { tableColumns } = this.state;
    const tmp = tableColumns.filter(item => item.fieldShow == 1);
    const columnsStateMap = {};
    tmp.forEach(item => {
      columnsStateMap[item.fieldName] = { show: false };
    });
    this.setState({
      columnsStateMap: { ...columnsStateMap },
    });
  };

  getColumns = () => {
    const count = this.getVisibleBtnCount({
      tags: [
        'initialdatareporting:cer-item-show',
        'initialdatareporting:cer-item-edit',
        'initialdatareporting:cer-dtshch',
      ],
    });

    const { tableColumns } = this.state;
    const colums = tableColumns.map((item, index) => {
      const { fieldLabel, fieldName, fieldWidth } = item;
      if (fieldName === 'qualified_status') {
        return {
          title: fieldLabel,
          dataIndex: fieldName,
          key: fieldName,
          fixed: 'left',
          width: 120,
          render: (text, record, index) => {
            // 是否有错误0未有错误1有错误
            const { is_have_error, error_message } = record;
            if (is_have_error === 0) {
              return <div className={styles.successBox}>合格</div>;
            } else if (is_have_error === 1) {
              const arr = error_message ? error_message.split('|') : [];
              const messages = arr.map((item, index) => {
                return <div key={index}>{`${index + 1}.${item}`}</div>;
              });
              return (
                <div className={styles.errorBox}>
                  <span>不合格</span>
                  <Tooltip placement="top" title={<div>{messages}</div>}>
                    <Icon type="exclamation-circle" style={{ marginTop: '2px' }} />
                  </Tooltip>
                </div>
              );
            }
          },
        };
      } else {
        return {
          title: fieldLabel,
          dataIndex: fieldName,
          key: fieldName,
          width: fieldWidth > 0 ? fieldWidth : 200,
        };
      }
    });
    return [
      ...colums,
      {
        title: '创建时间',
        key: 'createDatetime',
        width: 220,
        render: (text, record, index) => {
          const { insert_datetime } = record;
          const str = moment(insert_datetime).format('YYYY-MM-DD HH:mm:ss');
          return str;
        },
      },
      {
        title: '操作',
        key: 'operateCol',
        // width: count * 80,
        width: count * 50,
        fixed: 'right',
        //TODO:这里因为tag问题所以无法显示按钮，暂时不知道怎么解决
        render: (text, record, index) => {
          // 是否有错误0未有错误1有错误
          const { is_have_error } = record;
          //用户登陆权限
          const arr1 = this.props.currentUser.roles;
          //所有管理员权限
          const arr2 = this.state.roles;
          // 权限判断
          for (let i = 0; i < arr1.length; i++) {
            const flag = arr2.includes(arr1[i]);
            if (flag) {
              if (is_have_error === 0) {
                return (
                  <div>
                    <PermissionsWidget tag={'initialdatareporting:cer-item-show'}>
                      <Button
                        type="primary"
                        size={'small'}
                        style={{ marginRight: '8px' }}
                        className={styles.mGreenBtn}
                        onClick={() => {
                          this.handlePreviewClick(record);
                        }}
                      >
                        查看
                      </Button>
                    </PermissionsWidget>
                    <PermissionsWidget tag={'initialdatareporting:cer-dtshch'}>
                      <Popconfirm
                        title="确定执行当前操作吗?"
                        onConfirm={() => {
                          this.handleSingleDeleteClick(record);
                        }}
                      >
                        <Button type="danger" size={'small'}>
                          删除
                        </Button>
                      </Popconfirm>
                    </PermissionsWidget>
                  </div>
                );
              } else if (is_have_error === 1) {
                return (
                  <div>
                    <PermissionsWidget tag={'initialdatareporting:cer-item-edit'}>
                      <Button
                        type="primary"
                        size={'small'}
                        style={{ marginRight: '8px' }}
                        onClick={() => {
                          this.handleEditClick(record);
                        }}
                      >
                        修改
                      </Button>
                    </PermissionsWidget>
                    <PermissionsWidget tag={'initialdatareporting:cer-dtshch'}>
                      <Popconfirm
                        title="确定执行当前操作吗?"
                        onConfirm={() => {
                          this.handleSingleDeleteClick(record);
                        }}
                      >
                        <Button type="danger" size={'small'}>
                          删除
                        </Button>
                      </Popconfirm>
                    </PermissionsWidget>
                  </div>
                );
              }
            }
          }
        },
      },
    ];
  };

  /**
   * 批量删除
   */
  batchDeletion = () => {
    if (this.props.isBatchDeling) {
      return;
    }
    if (this.state.selectedRows.length === 0) {
      this.errorMessage('请先选择需要删除的记录');
      return;
    }
    let arr = [];
    this.state.selectedRows.map((row, index) => {
      arr.push(row.id);
    });
    let data = '';
    arr.map((item, index) => {
      data += `${item}|`;
    });
    this.execHttp('initialdatareporting/batchDeletion', {
      data: data,
    }).then(resp => {
      const { success } = resp;
      if (success) {
        this.clearAllSelectedRows().then(() => {
          this.listAllByPage();
        });
      }
    });
  };

  /**
   * 一键删除
   */
  oneClickDelete = () => {
    if (this.props.isDeleteAlling) {
      return;
    }
    this.execHttp('initialdatareporting/oneClickDelete', {
      user: this.props.currentUser.id,
    }).then(resp => {
      const { success } = resp;
      if (success) {
        this.clearAllSelectedRows().then(() => {
          this.listAllByPage();
        });
      }
    });
  };

  /**
   * 存入正式库
   */
  insertOfficeInfo = () => {
    if (this.props.isInsertOfficeInfo) {
      return;
    }
    this.execHttp('initialdatareporting/insertOfficeInfo', {
      user: this.props.currentUser.id,
    }).then(resp => {
      const { success } = resp;
      if (success) {
        const {
          data: { count },
        } = resp;
        debugger;
        this.successMessage(`更新成功,已更同步数据${count}条`);
        this.listAllByPage();
      }
    });
  };

  /**
   * 导出初始数据excel
   * */
  onExportClick = () => {
    if (this.props.isExporting) {
      return;
    }
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      this.errorMessage('请先选择需要导出的记录');
      return;
    } else {
      const hide = this.loadingMessage('正在导出数据,请稍后...');
      this.execHttp('initialdatareporting/exportSysteminitImportInfo', {
        user: this.props.currentUser.id,
        ids: selectedRowKeys.join('|'),
      })
        .then(response => {
          hide();
          saveAs(response, '初始数据上报' + '.xlsx');
        })
        .catch(error => {
          hide();
        });
    }
  };

  render() {
    const { data } = this.props;
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows({ selectedRowKeys, selectedRows });
      },
    };

    const uploadProps = {
      name: 'file',
      action: `/api/file/file/uploadFile4CerDataInit?user=${this.props.currentUser.id}`,
      accept: '.xlsx,.xls',
      headers: {
        authorization: 'authorization-text',
      },
      onChange: info => {
        if (info.file.status !== 'uploading') {
          this.setState(
            {
              fileList: info.fileList,
              // uploadLoading: true,
            },
            () => { }
          );
        }
        if (info.file.status === 'done') {
          if (this.hide) {
            this.hide();
          }
          this.setState({
            uploadLoading: false,
          });
          this.successMessage('上传成功,请等待后台处理');
        } else if (info.file.status === 'error') {
          this.errorMessage('文件上传出错,请联系管理员');
        }
      },
    };

    return (
      // "initialdatareporting:cer-import"
      <div className={styles.initialDataReporting}>
        <Card bordered={true} title={'初始数据上报'}>
          <SearchForm
            wrappedComponentRef={searchform => (this.searchform = searchform)}
            dictSex={this.state.xbcode}
            cities={this.state.cities}
            districtAndStreet={this.state.districtAndStreet}
            dictIsHaveError={this.state.isHaveError}
            isAdmin={this.state.isAdmin}
            onSearchClick={this.handleOnSearchClick}
            onCityChange={this.handleOnCityChange}
            onResetClick={this.handleReset}
            onExportClick={this.onExportClick}
          ></SearchForm>
          <PhotoProvider bannerVisible={false} maskOpacity={0.9}>
            <Row style={{ marginTop: '8px' }}>
              <Col
                span={24}
                style={{ marginTop: '8px', display: 'flex', justifyContent: 'flex-end' }}
              >
                <PermissionsWidget tag={'initialdatareporting:cer-import'}>
                  <Upload
                    {...uploadProps}
                    beforeUpload={this.handleUploadBefore}
                    showUploadList={false}
                    disabled={this.state.uploadLoading}
                  >
                    <Button type="primary" loading={this.state.uploadLoading}>
                      数据导入
                    </Button>
                  </Upload>
                </PermissionsWidget>
                <PermissionsWidget tag={'initialdatareporting:cer-download'}>
                  <Button
                    type="primary"
                    style={{ marginLeft: 8 }}
                    onClick={this.handleDownloadTempleteClick}
                  >
                    下载模版
                  </Button>
                </PermissionsWidget>

                <PermissionsWidget tag={'initialdatareporting:cer-bldm'}>
                  <PhotoView src={binglidaima}>
                    <Button type="primary" style={{ marginLeft: 8 }} className={styles.mGreenBtn}>
                      病理代码
                    </Button>
                  </PhotoView>
                </PermissionsWidget>

                <PermissionsWidget tag={'initialdatareporting:cer-xygz'}>
                  <PhotoView src={chushixiaoyanguize}>
                    <Button type="primary" style={{ marginLeft: 8 }} className={styles.mGreenBtn}>
                      校验规则
                    </Button>
                  </PhotoView>
                </PermissionsWidget>

                <PermissionsWidget tag={'initialdatareporting:cer-njzdmc'}>
                  <Button
                    type="primary"
                    style={{ marginLeft: 8 }}
                    className={styles.mGreenBtn}
                    onClick={this.handleDownloadDiagnosisNounsClick}
                  >
                    内镜诊断名词
                  </Button>
                </PermissionsWidget>

                <PermissionsWidget tag={'initialdatareporting:cer-plsc'}>
                  <Popconfirm title="确定执行当前操作吗?" onConfirm={this.batchDeletion}>
                    <Button
                      type="danger"
                      style={{ marginLeft: 8 }}
                      loading={this.props.isBatchDeling}
                    >
                      批量删除
                    </Button>
                  </Popconfirm>
                </PermissionsWidget>

                <PermissionsWidget tag={'initialdatareporting:cer-yjsc'}>
                  <Popconfirm title="确定执行当前操作吗?" onConfirm={this.oneClickDelete}>
                    <Button
                      type="danger"
                      style={{ marginLeft: 8 }}
                      loading={this.props.isDeleteAlling}
                    >
                      一键删除
                    </Button>
                  </Popconfirm>
                </PermissionsWidget>

                <PermissionsWidget tag={'initialdatareporting:cer-crzsk'}>
                  <Popconfirm title="确定执行当前操作吗?" onConfirm={this.insertOfficeInfo}>
                    <Button
                      type="primary"
                      style={{ marginLeft: 8 }}
                      loading={this.props.isSaveOfficeing}
                    >
                      存入正式库
                    </Button>
                  </Popconfirm>
                </PermissionsWidget>
              </Col>
            </Row>
          </PhotoProvider>
        </Card>
        <Card bordered={true} className={styles.contentBox}>
          {this.props.isPreparing ? (
            <div className={styles.spinBox}>
              <Spin />
            </div>
          ) : (
            <ProTable
              bordered={true}
              search={false}
              rowKey={record => record.id}
              rowSelection={rowSelection}
              loading={this.props.isLoading}
              data={this.props.data}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columnsStateMap={this.state.columnsStateMap}
              onColumnsStateChange={map => {
                if (Object.keys(map).length > 0) {
                  this.setState({
                    columnsStateMap: map,
                  });
                } else {
                  this.initColumnsStateMap();
                }
              }}
              columns={this.getColumns()}
              onChange={this.handleBasicTableChange}
              options={{
                density: false,
                reload: false,
                fullScreen: false,
                setting: true,
              }}
              scroll={{ x: true }}
            />
          )}
        </Card>

        {/* {/* 编辑 */}
        {this.state.editViewVisible ? (
          <EditView
            onClose={this.handleEditViewClose}
            visible={this.state.editViewVisible}
            record={this.state.record}
            sg={this.state.sg}
            bm={this.state.bm}
            w={this.state.w}
            sgblCode={this.state.sgblCode}
            isHj={this.state.isHj}
            sezccode={this.state.sezccode}
            ache={this.state.ache}
            zldxLy={this.state.zldxLy}
            dye={this.state.dye}
            zlFs={this.state.zlFs}
            Hp={this.state.Hp}
            hpjcjg={this.state.hpjcjg}
            bmblCode={this.state.bmblCode}
            wblCode={this.state.wblCode}
            xbcode={this.state.xbcode}
            isHaveError={this.state.isHaveError}
            tag1={this.state.tag1}
            tag2={this.state.tag2}
            tag3={this.state.tag3}
            tag4={this.state.tag4}
            tag5={this.state.tag5}
            onSubmit={this.handleEditViewSubmit}
          ></EditView>
        ) : null} 

        {/*详情*/}
        {this.state.previewViewVisible ? (
          <PreviewView
            onClose={this.handlePreviewViewClose}
            visible={this.state.previewViewVisible}
            record={this.state.record}
            sg={this.state.sg}
            bm={this.state.bm}
            w={this.state.w}
            sgblCode={this.state.sgblCode}
            isHj={this.state.isHj}
            sezccode={this.state.sezccode}
            ache={this.state.ache}
            zldxLy={this.state.zldxLy}
            dye={this.state.dye}
            zlFs={this.state.zlFs}
            Hp={this.state.Hp}
            hpjcjg={this.state.hpjcjg}
            bmblCode={this.state.bmblCode}
            wblCode={this.state.wblCode}
            xbcode={this.state.xbcode}
            isHaveError={this.state.isHaveError}
            tag1={this.state.tag1}
            tag2={this.state.tag2}
            tag3={this.state.tag3}
            tag4={this.state.tag4}
            tag5={this.state.tag5}
          ></PreviewView>
        ) : null}
      </div>
    );
  }

  handleUploadBefore = (file, fileList) => {
    this.setState({ uploadLoading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };

  handleOnSearchClick = data => {
    // console.log(`查询内容:${JSON.stringify(data)}`);
    // todo:此处需要将区域信息传回后台

    let { njzl_time, insert_datetime, blbgTime, ...others } = data;
    let insertStart;
    let insertEnd;
    let njzlStart;
    let njzlEnd;
    let blbgDate;

    let params = { ...others };

    // 病理报告日期
    if (blbgTime) {
      blbgDate = blbgTime.format('YYYY-MM-DD');
      params['blbgDate'] = blbgDate;
    }

    // 内镜诊疗日期范围
    if (njzl_time && njzl_time.length == 2) {
      njzlStart = njzl_time[0].format('YYYY-MM-DD');
      njzlEnd = njzl_time[1].format('YYYY-MM-DD');
      params['njzlStart'] = njzlStart;
      params['njzlEnd'] = njzlEnd;
    }

    // 创建时间日期范围
    if (insert_datetime && insert_datetime.length == 2) {
      insertStart = insert_datetime[0].format('YYYY-MM-DD');
      insertEnd = insert_datetime[1].format('YYYY-MM-DD');
      params['insertStart'] = insertStart;
      params['insertEnd'] = insertEnd;
    }

    // console.log(`查询内容:${JSON.stringify(params)}`);

    this.clearAllSelectedRows().then(() => {
      this.listAllByPage(params);
    });
  };

  handleReset = () => {
    this.clearAllSelectedRows().then(() => {
      this.listAllByPage();
    });
  };

  handleSelectRows = ({ selectedRowKeys, selectedRows }) => {
    this.setState({
      selectedRows: selectedRows,
      selectedRowKeys: selectedRowKeys,
    });
  };

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.listAllByPage(params);
  };

  /**
   * 单删
   * @param record
   */
  handleSingleDeleteClick = record => {
    this.deleteById({ id: record.id });
  };

  /**
   * 编辑按钮被点击
   * @param record
   */
  handleEditClick = record => {
    this.findById({ id: record.id }).then(res => {
      this.setState({
        editViewVisible: true,
      });
    });
  };

  /**
   * 详情被点击
   * @param record
   */
  handlePreviewClick = record => {
    this.findById({ id: record.id }).then(res => {
      this.setState({
        previewViewVisible: true,
      });
    });
  };

  /**
   * 编辑视图关闭
   */
  handleEditViewClose = () => {
    this.setState({
      editViewVisible: false,
    });
  };

  /**
   * 关闭详情
   */
  handlePreviewViewClose = () => {
    this.setState({
      previewViewVisible: false,
    });
  };

  /**
   * 编辑页提交数据
   * @param data
   */
  handleEditViewSubmit = data => {
    const { record } = this.state;

    const { njzlTime, blbgTime } = data;
    data['id'] = record.id;
    if (njzlTime && njzlTime != '') {
      data['njzlTime'] = njzlTime.format('YYYY-MM-DD');
    }
    if (blbgTime && blbgTime != '') {
      data['blbgTime'] = blbgTime.format('YYYY-MM-DD');
    }

    this.updateRecord({ data });
  };

  /**
   * 重置选中
   */
  clearAllSelectedRows = () => {
    return new Promise(resolve => {
      this.setState(
        {
          selectedRows: [],
          selectedRowKeys: [],
        },
        () => {
          resolve();
        }
      );
    });
  };

  /**
   * 下载模版
   */
  handleDownloadTempleteClick = () => {
    window.open(dataInitTemplateDownloadUrl);
  };

  /**
   * 下载内镜诊断名词
   */
  handleDownloadDiagnosisNounsClick = () => {
    window.open(dataInitDiagnosisNounsDownloadUrl);
  };

  /**
   * 处理城市改变
   * @param value
   */
  handleOnCityChange = value => {
    if (value !== undefined) {
      this.getDistrictAndStreet(value);
    } else {
      this.setState({
        districtAndStreet: [],
      });
    }
  };
}

export default InitialDataReporting;
